package cn.ckx.coding.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import java.time.Duration;
import java.util.Random;

/**
 * RedisCacheConfig
 *
 * @author kuxin.cai
 */

@Slf4j
@EnableCaching
@Configuration
public class RedisCacheConfig {

    /**
     * 缓存有效时间
     * 单位 秒
     */
    private static final  int  CACHE_EXPIRE = 600;

    private final RedisProperties redisProperties;

    public RedisCacheConfig(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;    
    }
    
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration();
        redisConf.setHostName(redisProperties.getHost());
        redisConf.setPort(redisProperties.getPort());
        redisConf.setPassword(redisProperties.getPassword());
        redisConf.setDatabase(redisProperties.getDatabase());
        return new LettuceConnectionFactory(redisConf);
    }

    @Bean
    public RedisCacheConfiguration cacheConfiguration() {
        return RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(CACHE_EXPIRE+ new Random(50).nextInt()))
                .disableCachingNullValues();
    }
    
    @Bean
    public RedisCacheManager cacheManager() {
        return RedisCacheManager.builder(redisConnectionFactory())
                .cacheDefaults(cacheConfiguration())
                .transactionAware()
                .build();
    }

    /**
     * 自定义缓存key的生成类实现
     */
    @Bean("mKeyGenerator")
    public KeyGenerator myKeyGenerator() {
        return (object, method, params) -> object.getClass().getName() + ":" +params[0];
    }
}
